<!--
 * @Description: 
 * @Author: Cxy
 * @Date: 2023-04-21 14:08:55
 * @LastEditors: Cxy
 * @LastEditTime: 2024-08-20 15:08:24
 * @FilePath: \xy-admin\play\src\views\login\component\login.vue
-->

<script lang="ts" setup>
import passWordRuleFun from './rules'
import grapverif from './grapverif'
import type { FormInstance, FormRules } from 'element-plus'
import { XyIconRender } from '@/components/XyIcon'
import { storageRead, storageSet } from '@/utils/storage'
import { userStore } from '@/stores/user'
import I18n from '@/hooks/I18n'

const imgCode = ref('123f')
const ruleFormRef = ref<FormInstance>()
const { tt } = I18n(ruleFormRef)
const ruleForm = reactive({
  loginCode: 'SeaHappy',
  passWord: '123dfgdfg',
  verifCode: imgCode
})

const grapverifDom = ref()
const verifCodeCheck = (_: any, value: string, callback: (error?: string | Error) => void) => {
  if (!value) return callback(new Error(tt.value('loginReg.checkVerifText')))
  if (value.toUpperCase() !== imgCode.value.toUpperCase()) {
    ruleForm.verifCode = ''
    grapverifDom.value.getImgCode()
    return new Error(tt.value('loginReg.errorVerifText'))
  }
  callback()
}
const { passWordRule } = passWordRuleFun()
const rules = reactive<FormRules>({
  ...passWordRule,
  verifCode: [{ validator: verifCodeCheck, trigger: 'blur' }]
})

const forgotPasswordOper = () => ElMessage.warning('请联系管理员')

onMounted(() => document.addEventListener('keydown', keydownOper))
onBeforeUnmount(() => document.removeEventListener('keydown', keydownOper))
const keydownOper = ({ key }: KeyboardEvent) => key === 'Enter' && loginOper(ruleFormRef.value)
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const loginOper = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      loading.value = true
      await userStore.login(ruleForm)
      loading.value = false
      const { path, query } = route.query
      if (path) {
        router.push({
          path: String(path),
          query: JSON.parse(String(query))
        })
      } else {
        router.push('/')
      }
    }
  })
}

const emit = defineEmits(['update:selectIndex'])
const regOper = () => emit('update:selectIndex', 1)

const rememberPassword = ref(storageRead('rememberPassword') || false)
watch(
  () => rememberPassword.value,
  curVal => storageSet('rememberPassword', curVal)
)
</script>

<template>
  <el-form ref="ruleFormRef" size="large" :model="ruleForm" :rules="rules" statusIcon>
    <el-form-item prop="loginCode">
      <el-input
        v-model="ruleForm.loginCode"
        :placeholder="tt('loginReg.accountText')"
        :prefixIcon="XyIconRender('ep/user-filled')"
      />
    </el-form-item>
    <el-form-item prop="passWord">
      <el-input
        v-model="ruleForm.passWord"
        :placeholder="tt('loginReg.passwordText')"
        :prefixIcon="XyIconRender('ic:baseline-lock')"
      />
    </el-form-item>
    <el-form-item prop="verifCode">
      <div class="login-verifCode">
        <el-input
          v-model="ruleForm.verifCode"
          :placeholder="tt('loginReg.verifText')"
          :prefixIcon="XyIconRender('ep/stamp')"
          @keyup.enter="loginOper(ruleFormRef)"
        />
        <grapverif ref="grapverifDom" v-model:code="imgCode" />
      </div>
    </el-form-item>
    <el-form-item>
      <div class="login-password">
        <el-checkbox v-model="rememberPassword">{{ tt('loginReg.rememberPasswordBtn') }}</el-checkbox>
        <el-button style="float: right" type="primary" link @click="forgotPasswordOper">
          {{ tt('loginReg.forgotPasswordBtn') }}
        </el-button>
      </div>
      <el-button :loading="loading" class="login-loginReg" type="primary" @click="loginOper(ruleFormRef)">
        <template #loading>
          <xyIcon style="margin-right: 6px" icon="line-md:loading-twotone-loop" />
        </template>
        {{ tt('loginReg.loginBtn') }}
      </el-button>
      <el-button class="login-loginReg" @click="regOper">{{ tt('loginReg.regBtn') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
.login-verifCode {
  width: 100%;
  font-size: 0;
  display: flex;

  :deep(.el-input) {
    .el-input__wrapper {
      border-radius: pxToRem(4) 0 0 pxToRem(4);
    }
  }

  canvas {
    vertical-align: middle;
    border-radius: 0 pxToRem(4) pxToRem(4) 0;
    flex: 1;
  }
}

.login-password {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: pxToRem(-8);
}

.login-loginReg {
  width: calc(50% - pxToRem(6));
}
</style>
